<!--
    参数 ：
    uploadParam     Object  请求参数 必需
    isInt           Boolean   初始化请求 必需
    path            接口查询使用，同系统不同服务使用 必需
    readOnly        是否只读
-->

<style lang="less" scoped="scoped">
@import "fileOperation.less";
</style>
<template>
    <div class="fileOperation">
        <Row type="flex" justify="center">
            <Col span="6" style="flex-shrink: 0">
                <div class="tree">
                    <div class="fieldset">
                        <!--                    <fieldset>-->
                        <div class="fieldset-title"> <strong> 资料列表</strong></div>

                        <div class="fileOperation-box">
                            <Tree :data="treeData"
                                  ref="tree"
                                  @on-select-change="selectTree"
                                  :render="renderContent"
                                  class="demo-tree-render"
                            ></Tree>
                        </div>
                        <!--                    </fieldset>-->
                    </div>
                </div>
            </Col>
            <Col span="18">
                <div class="fieldset">
                    <strong class="fieldset-title"> 资料内容</strong>
                    <Watermark :options="initWatermark"/>
                    <div>
                        <span>附件归类:</span>
                        <Select v-model="updateClassify"
                                placeholder="请选择附件类别"
                                :disabled="readOnly||!checkboxList.length || !checkedList.length"
                                @on-change="changeSelect"
                                style="width: 200px;">
                            <Option
                                v-for="(item,index) in classifyArray"
                                :value="item.id" :key="index"
                                :disabled="item.maxFileNums === item.validNums || item.id === updateClassify"
                            >{{item.title}}</Option>
                        </Select>
<!--                        <Button v-show="!readOnly" type="primary" icon="md-refresh" @click="updateFile">附件归类</Button>-->
                        <Button type="primary"  @click="downloadFile">附件下载</Button>
                        <Button type="primary" @click="viewFile">附件预览</Button>
                        <!--<LeaseFileUpload @afterUpload="messageUpload" @deleteFile="deleteFile" style="float:left;"></LeaseFileUpload>-->
<!--                        <label class="selectFile"><input type="checkbox" v-model='checked' @click='checkedAll'-->
<!--                                                         style="display:none;"/>选择(全选/反选)</label>-->
                        <div class="isAdminUpload" v-if="isAdminUpload">
<!--                            <Tooltip content="上传数量不限制" placement="bottom">-->
                            <span>补充上传：</span>
                            <i-switch v-model="isUploadShow" />
<!--                            </Tooltip>-->
                        </div>
                    </div>
                    <div style="padding-top: 10px;" v-show="!readOnly && !onlyUpload && checkboxList.length">
                        <Checkbox :value="checked" @on-change='checkedAll'>全选</Checkbox>
                        <Button  type="error" @click="deleteFile" style="margin-left: 10px;" >批量删除</Button>
                    </div>
                    <div id="watermark_bg" class="pr" v-show="attachmentClass">
                        <div class="showImgList">
                            <div v-for="(item,index) in checkboxList" :key="index" class="imgCheckListBox">
                                <div class="imgCheckList">
                                    <div class="img">
                                        <img :src="item.thumSrc"/>
                                    </div>
                                    <div class="icon-box" @click="viewSingleFile(item)">
                                        <!-- <span v-if="item.fileStatus === 'draft'" class="iconType"> 待审核</span> -->
                                        <span v-if="item.fileStatus === 'standard'" class="iconType success">合格</span>
                                        <span v-else-if="item.fileStatus === 'notStandard'"
                                              class="iconType fail">不合格</span>
                                        <span v-else-if="item.fileStatus === 'waitApprove'"
                                              class="iconType fail">待审核</span>
                                        <span v-if="!onlyUpload&&!readOnly" class="iconTypeMore delImg" @click.stop="deleteSingleFile(item)"><Icon type="ios-close" /></span>
<!--                                        <Checkbox v-if="!onlyUpload" class="iconTypeMore checkImg" :class="item.isChecked ? 'checked': ''"  :value="item.isChecked" @click.native.stop="selectCheckBox(item)">-->
<!--                                            <Icon type="ios-checkmark" />-->
<!--                                        </Checkbox>-->
                                        <span v-if="!onlyUpload" class="iconTypeMore checkImg" :class="item.isChecked ? 'checked': ''"  :value="item.isChecked" @click.stop="selectCheckBox(item)">
                                            <Icon type="ios-checkmark" />
                                        </span>
                                    </div>
<!--                                    <input type="checkbox" v-model='checkedList' :value="item.id">-->
                                </div>
                                    <Tooltip :content="item.fileName" placement="bottom">
                                        <span class="title">{{ item.fileName }}</span>
                                    </Tooltip>
                            </div>
                        </div>
                        <div class="drapFile" v-show="isUploadShow && !readOnly">
                            <LeaseFileUpload ref="leaseFileUpload" :modal="modal" @afterUpload="messageUpload" @deleteFile="cancelFile"
                                             tableMaxHeight="200"></LeaseFileUpload>
                        </div>
                    </div>
                </div>
            </Col>
            <div v-if="isShowModel">
                <filePreview :showFileList="showFileList" :path="path" :currentIndex="currentIndex" :isShowThumImg="false"
                             @close-img-model="closeImgModel"></filePreview>
            </div>
        </Row>
        <Spin size="large" fix v-if="loading"></Spin>
    </div>
</template>
<script>
import Vue from 'vue';
import {
    getUploadList,
    uploadFile,
    showFile,
    updateFile,
    deleteFile,
    downloadFile,
    getBlob,
} from "_p/basic/api/image/image-upload";
import LeaseFileUpload from '_c/file-upload/index';
import filePreview from "./filePreview.vue";
import getUploadTree from "../defines/getUploadTree";

import {getImgBlogUrl} from "_p/basic/api/image/image-getImgBlogUrl";
import {deepClone} from "@/libs/utils/ObjectClone";
import pdfImg from "_p/basic/assets/img/pdf.png";
import wordImg from "_p/basic/assets/img/word.jpg";
import {getUri} from "@/libs/tools";
import Watermark from "_p/basic/pages/image/file-audit/Watermark"

Vue.prototype.getUploadTree = getUploadTree;
export default {
    components: {
        Watermark,
        LeaseFileUpload,
        filePreview
    },
    props: {
        uploadParam: {
            type: Object
        },
        isInt: {
            type: Boolean,
            default: false,
            require: true,
        },
        //接口查询使用，同系统不同服务使用
        path: {
            type: String,
        },
        readOnly: {
            type: Boolean,
            default: false,
        },
        onlyUpload:{
            type: Boolean,
            default: false,
        },
        isAdminUpload:{
            type: Boolean,
            default: false,
        },
    },
    data() {
        return {
            loading: false, //
            fileList: 0,
            checkboxList: [],
            checked: false, //全选框
            modal: false,
            checkedList: [],
            showFileList: [], //预览需要展示的部分
            isShowModel: false,//是否展示model
            currentSelectedTreeNodes: null, // 当前选中的树节点
            classifyArray: [],
            prevClassify: null, // 下拉框上一个选中的点
            updateClassify: "",
            attachmentClass: null,
            attachmentSubClass: "",
            treeData: [],
            selectedFileList: [],
            param: {},
            initParam: {},
            applyNo: this.uploadParam.busiNo,
            belongNo: this.uploadParam.belongNo,
            busiType: this.uploadParam.busiType,
            busiData: this.uploadParam.busiData,
            isUploadShow: false,
            maxFileNums: null,
            minFileNums: null,
            watermarkTitle: null,
        }
    },
    watch: { //深度 watcher
        'checkedList': {
            handler: function (val, oldVal) {
                if (this.checkboxList.length > 0 && val.length === this.checkboxList.length) {
                    this.checked = true;
                } else {
                    this.checked = false;
                }
            },
            deep: true
        },
        isInt(val) {
            console.log('isInt(val)', val);
            if (val) {
                this.currentSelectedTreeNodes = null; // 当前选中的树节点
                this.classifyArray = []
                this.checkedList = []
                this.watermarkTitle = null
                this.attachmentClass = null;
                this.updateClassify = null;
                this.init()
            }else {
                this.isShowModel=false
            }
        }
    },
    mounted() {
        this.init();
    },
    computed: {
        initWatermark() {
            return {
                text: this.watermarkTitle,
                textColor: "rgba(237,64,20,.1)",
                width: 500,
                height: 400,
                font: '30px Vedana',
            }
        },
    },
    created() {
        console.log(this.$route.meta.menusParams,'console.log(this.afs.getMenuParams(this));',this.afs.getMenuParams(this));
        const  _uploadConfigApi = this.afs.getMenuParams(this);
        this._uploadConfigApi = _uploadConfigApi || {}
            // {_uploadSaveConfigApi,_uploadDeleteConfigApi,_uploadUpdateConfigApi}
    },
    methods: {
        init() {
            if (this.isInt) {
                this.getTree();
                // this.selectTree();
            }
        },
        renderContent(h, {root, node, data}) {
            let color= 'white',
                fontWeight = data.attachmentClass === 1 ? 600 : 400,
                maxFile = null;
            if (data.needNums > 0 || data.needType == 1) {
                color= 'red'
            }
            if(data.attachmentClass === 3 ) {
                maxFile =  h('span',
                    {style: { float: 'right',color:'#EB9620' }},
                    typeof data.validNums === 'number' && data.maxFileNums ? (data.validNums + '/' + data.maxFileNums) : ''
                ) //maxFileNums
            }
            return h('span', {
                class:'tree-item'
            }, [h('span',{class: ['tree-label',color],style:{fontWeight}},data.title), maxFile]);
        },
        getTree() {
            const {uploadParam,path,_uploadConfigApi = {},currentSelectedTreeNodes} = this;
            console.log(_uploadConfigApi._uploadGetUploadConfigApi,"_uploadConfigApi");
            // this.loading = true;
            getUploadList(uploadParam, path, _uploadConfigApi._uploadGetUploadConfigApi).then(res => {
                this.loading = false;
                if (res.code === "0000") {
                    this.treeData = this.getUploadTree(res.data,currentSelectedTreeNodes);
                    let classifyArr = []
                    Array.isArray(this.treeData) && this.treeData.forEach(c => {
                        if (c.attachmentClass === 3) {
                            let obj = {id: c.id, title: c.title,maxFileNums:c.maxFileNums,validNums:c.validNums};
                            classifyArr.push(obj);
                            this.initFlags(c);
                        }
                        if (c.attachmentClass === 2 && c.children && c.children.length > 0) {
                            c.children.forEach(s => {
                                if (s.attachmentClass === 3) {
                                    let obj = {id: s.id, title: s.title,maxFileNums:s.maxFileNums,validNums:s.validNums};
                                    classifyArr.push(obj);
                                    this.initFlags(s);
                                }
                            })
                        }
                        if (c.attachmentClass === 1 && c.children && c.children.length > 0) {
                            c.children.forEach(s => {
                                if (s.attachmentClass === 3) {
                                    let obj = {id: s.id, title: s.title,maxFileNums:s.maxFileNums,validNums:s.validNums};
                                    classifyArr.push(obj);
                                    this.initFlags(s);
                                }
                                if (s.attachmentClass === 2 && s.children && s.children.length > 0) {
                                    s.children.forEach(i => {
                                        if (i.attachmentClass === 3) {
                                            let obj = {id: i.id, title: i.title,maxFileNums:i.maxFileNums,validNums:i.validNums};
                                            classifyArr.push(obj);
                                            this.initFlags(i);
                                        }
                                    })
                                }
                            })
                        }
                    })
                    console.log('classifyArray',classifyArr)
                    this.classifyArray = classifyArr
                }
            }).catch(e => {
                this.loading = false;
                console.error(e)
            });
        },
        changeSelect(id) {
            if(!id) return ;
            let item = this.classifyArray.find(e => e.id === id)
            console.log(id,'---changeSelect----',item)
            if(item) {
                if(item && (item.maxFileNums - item.validNums >= this.checkedList.length)) {
                    this.updateFile()
                    this.prevClassify = id;
                }else {
                    this.$Message.warning(item.title+'已超出最大文件数量')
                    this.updateClassify = this.prevClassify
                }
            }
        },
        messageUpload(uploadInfo) {
            console.log(uploadInfo, "uploadInfo");
            // this.loading = true;
            let selectedNode = this.$refs.tree.getSelectedNodes()[0];
            if (selectedNode) {
                let {busiNo, belongNo} = this.uploadParam; // busiNo == this.applyNo; belongNo == this.belongNo

                let attachmentId = selectedNode.id;
                let attachmentName = selectedNode.title;
                let fileType = uploadInfo.fileType;
                let fileName = uploadInfo.name;
                let fileMd5 = uploadInfo.fileMd5;
                uploadFile(attachmentId, attachmentName, fileType, fileName, fileMd5, busiNo, belongNo, this.path,this._uploadConfigApi._uploadSaveConfigApi).then(res => {
                    if (res.code === "0000") {
                        // this.showFile(selectedNode);
                        this.getTree()
                    }
                    this.loading = false;
                }).catch(e => {
                    this.loading = false;
                    console.error(e)
                });
            }
        },
        selectTree() {
            let selectNode = this.$refs.tree.getSelectedNodes()[0];
            // this.$refs.leaseFileUpload.$children[0].fileList=[];
            console.log("selectNode", selectNode)
            if (selectNode) {
                this.cancelFiles()
                this.currentSelectedTreeNodes = selectNode; //当前选中的树
                this.watermarkTitle = selectNode.title;
                this.attachmentClass = selectNode.attachmentClass;
                this.updateClassify = selectNode.id;
                this.showFile(selectNode);
                this.checkedList = [];
            } else {
                this.attachmentClass = 0;
            }
        },
        showFile(selectNode) {
            let {busiNo, belongNo} = this.uploadParam;
            let showParams = {busiNo: "", belongNo: "", comAttachmentManagement: {}};
            showParams.busiNo = busiNo;
            showParams.belongNo = belongNo;
            showParams.comAttachmentManagement = selectNode;
            // this.loading = true;
            showFile(showParams, this.path).then(res => {
                this.loading = false;

                if (res.code === "0000") {
                    let fileList = res.data.fileList;
                    let authorization = res.data.authorization
                    this.authorization = authorization;
                    let list = [],
                        dataList = []
                    if (fileList.length > 0) {
                        fileList.forEach(async (file, index) => {
                            file.fileType = file.fileType.toLowerCase();
                            if (file.fileStatus !== "standard") {
                                this.isUploadShow = true;
                            }
                            if (file.fileType === "jpg" || file.fileType === 'png' || file.fileType === 'jpg' || file.fileType === 'jpeg') {
                                // let url= await getBlob(file.fileId,file.fileName);
                                let url = `${_AFS_PROJECT_CONFIG.apiUri}/${this.path}/upload/getBlob/${file.fileType}/${file.fileId}`;
                                dataList.push(Object.assign({}, file, {thumSrc: url, imgSrc: url}))
                            } else if (file.fileType === "pdf") {
                                let url = `${_AFS_PROJECT_CONFIG.apiUri}/${this.path}/upload/getBlob/${file.fileType}/${file.fileId}`;
                                dataList.push(Object.assign({}, file, {thumSrc: pdfImg, imgSrc: url}))
                            } else if (file.fileType === "docx" || file.fileType === "doc") {
                                dataList.push(Object.assign({}, file, {thumSrc: wordImg, imgSrc: ""}))
                            }
                        })
                    } else {
                        this.isUploadShow = true;
                    }

                    console.log('fileList', dataList);
                    this.checkboxList = dataList;
                    this.fileList = dataList.length;
                    if (!isNaN(selectNode.maxFileNums)&&!isNaN(selectNode.validNums)) {
                        selectNode.validNums >= selectNode.maxFileNums
                            ? this.isUploadShow = false
                            : this.isUploadShow = true
                    }
                }
            }).catch(e => {
                this.loading = false;
                console.error(e)
            });
        },
        initFlags(data) {
            if (data.selected == true) {
                // console.log(data,'------')
                this.watermarkTitle = data.title;
                this.updateClassify = data.id;
                this.prevClassify = data.id;
                this.showFile(data);
                this.attachmentClass = data.attachmentClass;
            }
        },
        updateFile() {
            let filelist = this.updateChecked();
            // this.loading = true;

            updateFile(filelist, this.path,this._uploadConfigApi._uploadUpdateConfigApi).then(res => {
                this.loading = false;
                if (res.code === "0000") {
                    // this.init()
                    // this.selectTree();
                    this.getTree()
                    this.checkedList = [];
                }
            }).catch(e => {
                this.loading = false;
                console.error(e)
            });
        },
        collectChecked() {
            console.log(this.checkedList, "collectChecked _this.checkedList");
            let checkedFiles = [];
            this.checkedList.forEach((id, index) => {
                let item = this.checkboxList.find(e => e.id === id)
                if(item) {
                    let type = item.fileType;
                    if (type.indexOf("png,jpg,jpeg,gif,bmp")) {
                        type = "img";
                    }
                    checkedFiles.push(Object.assign({},item,{type,imageFlow:''}));
                }
            })
            return checkedFiles;
        },

        backChecked() {
            console.log(this.checkedList, "backChecked _this.checkedList");
            let checkedFiles = [];
            this.checkedList.forEach((id, index) => {
                this.checkboxList.forEach((item, index) => {
                    if (id == item.id) {
                        let type = item.fileType;
                        let imageType = "png,jpg,jpeg,gif,bmp";
                        if (type.indexOf(imageType)) {
                            item.type = "img";
                        } else {
                            item.type = item.fileType;
                        }
                        item.imageFlow = "";
                        item.imageUrl = "";
                        item.thumUrl = "";
                        checkedFiles.push(item);
                    }
                })
            })
            return checkedFiles;
        },

        updateChecked() {
            console.log(this.checkedList, "updateChecked _this.checkedList");
            let attachmentId = this.updateClassify;
            let checkedFiles = {attachmentId: attachmentId, fileList: []};
            this.checkedList.forEach((id, index) => {
                this.checkboxList.forEach((item, index) => {
                    if (id == item.id) {
                        let file = {id: ""}
                        file.id = id;
                        checkedFiles.fileList.push(file);
                    }
                })
            })
            return checkedFiles;
        },

        deleteChecked() {
            console.log(this.checkedList, "deleteChecked _this.checkedList");
            let checkedFiles = {fileList: []};
            let arr = []
            this.checkedList.forEach((id, index) => {
                this.checkboxList.forEach((item, index) => {
                    if (id == item.id) {
                        let file = {id: ""}
                        file.id = id;
                        if (item.fileStatus == "draft") {
                            if(item.isElectronic !== "1"){
                                arr.push(item.fileId)
                                checkedFiles.fileList.push(file);
                            }else{
                                this.$Message.error("电子签文件不允许删除！");
                                return;
                            }
                        } else {
                            this.$Message.error("已审核的影像件不允许删除！");
                        }
                    }
                })
            })
            return [checkedFiles,arr];
        },
        selectCheckBox(item){
            let checkboxIndex = this.checkboxList.findIndex(e => e.id === item.id)
            let index = this.checkedList.findIndex(e => e === item.id)
            if(index >= 0) {
                this.checkboxList[checkboxIndex].isChecked = false ;
                this.checkedList.splice(index,1)
            }else {
                this.checkboxList[checkboxIndex].isChecked = true;
                this.checkedList.push(item.id)
            }
            console.log(item,index,this.checkedList)
        },
        //单个文件预览 预览全部文件
        viewSingleFile(current){
            // this.showFileList = [Object.assign({},item,{type:'img',imageFlow:''})];
            let checkedFiles = [],
                currentIndex = 0;
            this.checkboxList.forEach((item, index) => {
                    let type = item.fileType;
                    if(item.id === current.id) {
                        currentIndex = index
                    }
                    if (type.indexOf("png,jpg,jpeg,gif,bmp")) {
                        type = "img";
                    }
                    checkedFiles.push(Object.assign({},item,{type,imageFlow:''}));
            })
            this.currentIndex = currentIndex;
            this.showFileList = checkedFiles;
            this.isShowModel = true;
            this.$emit("open-img-model")
        },
        viewFile() {
            let filelist = this.collectChecked();

            if (filelist.length > 0) {
                this.showFileList = filelist;
                this.isShowModel = true;
                this.$emit("open-img-model")
            } else {
                this.$Message.warning('请选择需要预览的图片');
            }
        },
        //单个删除
        deleteSingleFile(item) {
            let list;
            if (item.id) {
                if (item.fileStatus === "draft") {

                    if(item.isElectronic !== "1"){
                        list = {fileList: [{id: item.id}]};
                    }else{
                        this.$Message.error("电子签文件不允许删除！");
                        return;
                    }
                } else {
                    this.$Message.error("已审核的影像件不允许删除！");
                    return;
                }
                // this.loading = true;
                this.cancelFiles([item.fileId])

                deleteFile(list, this.path, this._uploadConfigApi._uploadDeleteConfigApi).then(res => {
                    this.loading = false;
                    if (res.code === "0000") {
                        // this.selectTree();
                        this.getTree();
                        this.checkedList = [];
                    }
                }).catch(e => {
                    this.loading = false;
                    console.error(e)
                });
            }
        },
        deleteFile() {
            let filelist = this.deleteChecked();
            // this.loading = true;

            deleteFile(filelist[0], this.path,this._uploadConfigApi._uploadDeleteConfigApi).then(res => {
                this.loading = false;
                if (res.code === "0000") {
                    // this.selectTree();
                    // this.init()
                    this.getTree();
                    this.checkedList = [];
                    this.cancelFiles(filelist[1])
                }
            }).catch(e => {
                this.loading = false;
                console.error(e)
            });
        },
        downloadFile() {
            let checkedFiles = {data: []};
            let selectNode = this.$refs.tree.getSelectedNodes()[0];
            let self = this;
            if(this.checkedList.length === 0) {
                this.$Message.warning('请选择需要下载的图片');
                return ;
            }
            this.checkedList.forEach((id, index) => {
                this.checkboxList.forEach((item, index) => {
                    if (id == item.id) {
                        let md5Value = item.fileId;
                        let downloadsceneid = selectNode.busiNode;
                        let filename = item.fileName;
                        let isView = "0";//下载
                        let isThumb = "";//不传值表示下载原图
                        let downloadParam = {
                            md5Value: md5Value,
                            downloadsceneid: downloadsceneid,
                            filename: filename,
                            isView: isView,
                            isThumb: isThumb
                        };
                        checkedFiles.data.push(downloadParam);
                    }
                })
            })
            downloadFile(checkedFiles, this.path).then(function (response) {
                if (response.status === 200) {
                    self.afs.downloadFile(response)
                }
            });
        },
        // 取消上传
        cancelFile(item){
            // console.log('取消上传',item)
            let itm = this.checkboxList.find(e => e.fileId === item.fileMd5)
            this.deleteSingleFile(itm)
        },
        // 删除上传组件数据
        cancelFiles(arr){
            this.$refs.leaseFileUpload.cancelFiles(arr)
        },
        // 选择全选与反选
        checkedAll: function () {
            let checkedList = [],
                checkboxList = []
            if (this.checked) { //实现反选
                this.checkboxList.forEach(function (item, index) {
                    checkboxList.push(Object.assign({},item,{isChecked:false}))
                });
            } else { //实现全选
                this.checkboxList.forEach(function (item, index) {
                    checkboxList.push(Object.assign({},item,{isChecked:true}))
                    checkedList.push(item.id);
                });
            }
            this.checkboxList = checkboxList;
            this.checkedList = checkedList;
            console.log(this.checkedList)
        },
        closeImgModel(value) {
            this.isShowModel = value;
            let selectedNode = this.$refs.tree.getSelectedNodes()[0];
            this.showFile(selectedNode);
        },
        getFileList() {
            return this.fileList
        },
    }
}
</script>
<style scoped>
</style>
